package com.inspur.edp.common.expr.parser;

import com.inspur.edp.common.expr.ast.CompileUnitLexer;
import com.inspur.edp.common.expr.ast.CompileUnitParser;
import com.inspur.edp.common.expr.constant.ExpressResourceKey;
import com.inspur.edp.common.expr.exception.ExpressBizException;
import org.antlr.v4.runtime.*;

/**
 * @author lizhaorui
 * @date 2025/8/18
 * @description
 */
public class ASTParser {

    public static CompileUnitParser parse(String content) {
        CompileUnitLexer lexer = new CompileUnitLexer(CharStreams.fromString(content));
        CommonTokenStream tokens = new CommonTokenStream(lexer);
        CompileUnitParser parser = new CompileUnitParser(tokens);
        BaseErrorListener errorListener = new BaseErrorListener() {
            @Override
            public void syntaxError(Recognizer<?, ?> recognizer, Object offendingSymbol, int line, int charPositionInLine, String msg, RecognitionException e) {
                throw new ExpressBizException(ExpressResourceKey.PARSE_DSL_ERROR, null, true, line, charPositionInLine, msg, content);
            }
        };
        lexer.removeErrorListeners();
        lexer.addErrorListener(errorListener);
        parser.removeErrorListeners();
        parser.addErrorListener(errorListener);
        return parser;
    }

    public static String getRuleContextDsl(String dsl, ParserRuleContext ruleContext) {
        int start = ruleContext.getStart().getStartIndex();
        int stop = ruleContext.getStop().getStopIndex();
        return dsl.substring(start, stop + 1);
    }

}